package com.tabjin.rfidsocket.authority.shiro;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.tabjin.rfidsocket.common.RequestHolder;
import com.tabjin.rfidsocket.pojo.SysUser;
import com.tabjin.rfidsocket.pojo.vo.SysUserVO;
import com.tabjin.rfidsocket.service.sys.SysUserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author Tabjin
 * create at 2021/2/27 10:12
 * @program emos-wx-api
 * @description
 */
@Component
@Scope("prototype")// 变成多例对象，否则往ThreadLocal中保存数据会出现问题
public class OAuth2Filter extends AuthenticatingFilter {
    // options请求直接放行
    // 提交application
    @Autowired
    private ThreadLocalToken threadLocalToken;

    /**
     * 数据过期时间
     */
    @Value("${emos.jwt.cache-expire}")
    private Integer cacheExpire;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SysUserService sysUserService;

    /**
     * 拦截请求之后，用于把令牌字符串封装成令牌对象，令牌对象将交给Shiro框架使用
     *
     * @param request
     * @param servletResponse
     * @return
     * @throws Exception
     */
    @Override
    protected AuthenticationToken createToken(ServletRequest request, ServletResponse servletResponse) throws Exception {
        HttpServletRequest req = (HttpServletRequest) request;
        // 获取请求 token
        String token = getRequestToken(req);
        if (StringUtils.isBlank(token)) {
            return null;
        }
        return new OAuth2Token(token);// 封装令牌字符串
    }

    /**
     * 判断是否登录，在登录的情况下会走此方法，此方法返回true直接访问控制器
     * 拦截请求，判断请求是否需要被Shiro处理
     *
     * @param request
     * @param response
     * @param mappedValue
     * @return
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        HttpServletRequest req = (HttpServletRequest) request;
        // Ajax提交application/json数据的时候，会先发出Option请求
        // 这里要放行Option请求，不需要Shiro处理
        if (req.getMethod().equals(RequestMethod.OPTIONS.name())) {
            return true;
        }
        // 除了Options请求之外，所有请求都要被Shiro处理
        return false;
    }

    /**
     * 是否是拒绝登录，没有登录的情况下会走此方法
     * 该方法用于处理所有应该被Shiro处理的请求
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request,
                                     ServletResponse response) throws Exception {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        res.setContentType("text/html");
        res.setCharacterEncoding("UTF-8");
        // 允许跨域
        res.setHeader("Access-Control-Allow-Credentials", "true");
        res.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
        // 清空ThreadLocal中的数据，因为如果令牌需要刷新，不仅仅令牌要保存到Redis中，还要存到媒介类ThreadLocal
        threadLocalToken.clear();

        String token = getRequestToken(req);
        if (StringUtils.isBlank(token)) {
            res.setStatus(HttpStatus.SC_UNAUTHORIZED);
            res.getWriter().print("无效令牌");
            return false;// token有问题就不再执行认证和授权
        }
        try {
            jwtUtil.verifyToken(token);
        } catch (TokenExpiredException e) {
            // Token 过期异常
            // Redis 中缓存的令牌是否过期
            if (redisTemplate.hasKey(token)) {
                // 此时客户端令牌已过期，但是服务端令牌未过期，需令牌刷新
                redisTemplate.delete(token);// 先删
                Integer userId = jwtUtil.getUserId(token);// 旧令牌中获取userId
                token = jwtUtil.createToken(userId);
                redisTemplate.opsForValue().set(token, userId + "", cacheExpire, TimeUnit.DAYS);// 新生成的令牌保存到Redis
                threadLocalToken.setToken(token);// 新令牌也保存到媒介类中

//                SysUser sysUser = sysUserService.searchUserById(userId);
//                SysUserVO sysUserVO = new SysUserVO();
//                BeanUtils.copyProperties(sysUser, sysUserVO);
//                RequestHolder.add(sysUserVO);
            } else {
                // 客户端令牌过期，且服务端缓存的令牌过期被销毁，需要用户重新登录
                res.setStatus(HttpStatus.SC_UNAUTHORIZED);
                res.getWriter().print("令牌过期");
                return false;// token有问题就不再执行认证和授权
            }
        } catch (JWTDecodeException e) {
            // Token 内容异常（如客户端伪造令牌）
            res.setStatus(HttpStatus.SC_UNAUTHORIZED);
            res.getWriter().print("无效令牌");
            return false;// token有问题就不再执行认证和授权
        }

        // 令牌无问题，间接调用relam类
        boolean result = executeLogin(request, response);// 间接让Shiro执行realm类
        return result;
    }

    /**
     * Shiro在执行realm类中认证方法时，判定用户没有登录或者登陆失败的时候执行
     *
     * @param token
     * @param e
     * @param request
     * @param response
     * @return
     */
    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        // 往响应中写一些状态码和错误消息
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        res.setContentType("text/html");
        res.setCharacterEncoding("UTF-8");
        // 允许跨域
        res.setHeader("Access-Control-Allow-Credentials", "true");
        res.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
        res.setStatus(HttpStatus.SC_UNAUTHORIZED);
        try {
            res.getWriter().print(e.getMessage());// 认证失败的详细消息
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
        return false;// token有问题就不再执行认证和授权
    }

    /**
     * 掌管拦截请求和返回响应的方法，不具体实现了
     *
     * @param request
     * @param response
     * @param chain
     * @throws ServletException
     * @throws IOException
     */
    @Override
    public void doFilterInternal(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest req = (HttpServletRequest) request;
        RequestHolder.add(req);
        HttpServletRequest currentRequest = RequestHolder.getCurrentRequest();
        System.out.println("dddd");
        super.doFilterInternal(request, response, chain);
    }

    private String getRequestToken(HttpServletRequest request) {
        String token = request.getHeader("token");
        if (StrUtil.isBlank(token)) {
            token = request.getParameter("token");
        }
        return token;
    }
}
